import traceback

import pymssql
import pyodbc


def conn_sqlserver_demo():
    # 连接字符串示例（根据您的配置进行修改）
    conn = None
    try:
        conn = pymssql.connect(
            server=f"192.168.18.1",
            user="sa",
            password="126.com",
            database="ZMN22027",
        )
        cursor = conn.cursor()
        sql = "SELECT ROW_NUMBER() OVER (ORDER BY t.TABLE_NAME) AS 序号, t.TABLE_NAME AS 表名, c.value AS 注释 FROM INFORMATION_SCHEMA.TABLES AS t LEFT JOIN sys.extended_properties AS c ON OBJECT_ID(t.TABLE_NAME) = c.major_id AND c.minor_id = 0 AND c.name = 'MS_Description'"
        cursor.execute(sql)
        for row in cursor:
            print(row)
    except Exception as e:
        traceback.print_exc()  # 回调函数，输出异常信息
        conn.rollback()
        print("连接数据库时发生错误:", str(e))
    finally:
        conn.close()

def conn_sqlserver_demo2():
    odbc_conn_str = "DRIVER={ODBC Driver 18 for SQL Server};SERVER=192.168.18.1;UID=sa;PWD=126.com;DATABASE=ZMN22027;"
    cn = pyodbc.connect(odbc_conn_str)
    sql = "SELECT ROW_NUMBER() OVER (ORDER BY t.TABLE_NAME) AS 序号, t.TABLE_NAME AS 表名, c.value AS 注释 FROM INFORMATION_SCHEMA.TABLES AS t LEFT JOIN sys.extended_properties AS c ON OBJECT_ID(t.TABLE_NAME) = c.major_id AND c.minor_id = 0 AND c.name = 'MS_Description'"
    cn.execute(sql)
if __name__ == "__main__":
    # 当脚本作为主程序运行时，调用启动函数
    conn_sqlserver_demo2()
